﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PowerBooking.RSE.Domain.Models;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Reflection;
using System.Threading;
using System.Data.Entity;
using PowerBooking.RSE.Repository;
using System.Runtime.Caching;
using PowerBooking.RSE.Utility.Helpers;
using System.Data.Objects;

namespace PowerBooking.RSE.Domain.Factories
{
    /// <summary>
    /// 蜘蛛工厂
    /// </summary>
    public class SpiderFactory : Factory
    {
        public SpiderFactory(ObjectContext objectContext) : base(objectContext) { }

        /// <summary>
        /// 获取一只蜘蛛
        /// </summary>
        /// <param name="spiderID"></param>
        /// <returns></returns>
        public Spider GetSpiderBySpiderID(int spiderID)
        {
            return new Spider().InitDomain(SpiderRepository.GetSpiderBySpiderID(spiderID));
        }

        /// <summary>
        /// 创建蜘蛛集合
        /// </summary>
        /// <returns></returns>
        public List<Spider> CreateSpiders()
        {
            var cityFactory = new CityFactory(Context);
            var spiderRepository = new SpiderRepository(Context);
            var spiderPocoList = spiderRepository.GetAllSpiders();
            var spiders = new ConcurrentBag<Spider>();
            Parallel.ForEach(spiderPocoList, (s, loopState) =>
            {
                if (!CacheHelper.Get<bool>("IsCaptureStop"))
                {
                    var createCityMethod = cityFactory.GetType().GetMethod(string.Format("Create{0}Cities", s.Name));
                    var cities = (List<City>)createCityMethod.Invoke(cityFactory, new object[] { s.SpiderID, s.Url });
                    spiders.Add(new Spider().InitDomain(s).InitCities(cities));
                }
                else
                {
                    loopState.Stop();
                    return;
                }
            });
            return spiders.ToList();
        }
    }
}
